﻿using ArcGIS.Core.Data;
using ArcGIS.Core.Data.UtilityNetwork.Trace;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using CCTool.Scripts.Manager;
using CCTool.Scripts.ToolManagers;
using CCTool.Scripts.ToolManagers.Extensions;
using CCTool.Scripts.ToolManagers.Managers;
using NPOI.OpenXmlFormats.Vml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Polygon = ArcGIS.Core.Geometry.Polygon;
using Polyline = ArcGIS.Core.Geometry.Polyline;

namespace CCTool.Scripts.DataPross.FeatureCheck
{
    /// <summary>
    /// Interaction logic for SearchOverlapPoint.xaml
    /// </summary>
    public partial class SearchOverlapPoint : ArcGIS.Desktop.Framework.Controls.ProWindow
    {
        // 工具设置标签
        readonly string toolSet = "SearchOverlapPoint";

        public SearchOverlapPoint()
        {
            InitializeComponent();

            // 初始化参数选项
            txt_digit.Text = BaseTool.ReadValueFromReg(toolSet, "digit", "3");

        }

        // 定义一个进度框
        private ProcessWindow processwindow = null;
        string tool_name = "查找面要素的重叠界址点";

        private async void btn_go_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取指标
                string layerName = combox_fc.ComboxText();
                int digit = txt_digit.Text.ToInt();

                string gdbPath = Project.Current.DefaultGeodatabasePath;

                // 判断参数是否选择完全
                if (layerName == "")
                {
                    MessageBox.Show("有必选参数未填写！");
                    return;
                }
                if (digit <= 0)
                {
                    MessageBox.Show("请填写正确的容差位数");
                    return;
                }

                // 写入本地
                BaseTool.WriteValueToReg(toolSet, "digit", digit);

                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);

                Close();

                await QueuedTask.Run(() =>
                {
                    pw.AddMessageStart("获取参数");

                    string outName = $@"{layerName}_查找重叠界址点";
                    string outPath = $@"{gdbPath}\{outName}";

                    string message = $"查找图层【{layerName}】的重叠界址点";
                    pw.AddMessageMiddle(20, message);


                    // 修改坐标点
                    List<string> xys = new List<string>();

                    // 获取图层
                    FeatureLayer featurelayer = layerName.TargetFeatureLayer();
                    // 获取目标的坐标系
                    SpatialReference sr = featurelayer.GetSpatialReference();
                    // 获取图层的要素类
                    FeatureClass featureClass = layerName.TargetFeatureClass();

                    // 遍历面要素类中的所有要素(有选择就按选择)
                    RowCursor rowCursor = featureClass.Search();

                    // 遍历图层的要素
                    while (rowCursor.MoveNext())
                    {
                        using Feature feature = (Feature)rowCursor.Current;

                        // 获取要素的几何
                        Polygon polygon = feature.GetShape() as Polygon;
                        // 获取几何的所有段
                        var parts = polygon.Parts.ToList();

                        foreach (ReadOnlySegmentCollection collection in parts)
                        {
                            // 每个环进行处理（第一个为外环，其它为内环）
                            foreach (Segment segment in collection)
                            {
                                MapPoint mapPoint = segment.StartPoint;     // 获取点
                                // 坐标转字符串，保留3位小数
                                string xy = $"{mapPoint.X.RoundWithFill(3)}+{mapPoint.Y.RoundWithFill(3)}";
                                xys.Add(xy);
                            }
                        }

                    }

                    // 查找xys的重复项
                    List<string> repeat = xys.GroupBy(x => x).Where(g => g.Count() > 1).Select(y => y.Key).ToList();

                    pw.AddMessageMiddle(40, "创建锐角点");

                    List<MapPoint> mapPoints = new List<MapPoint>();
                    // xys转成MapPoint
                    foreach (string xy in repeat)
                    {
                        string[] xy_split = xy.Split('+');
                        double x = xy_split[0].ToDouble();
                        double y = xy_split[1].ToDouble();
                        MapPointBuilderEx mapPointBuilderEx = new(new Coordinate2D(x, y));
                        MapPoint mapPoint = mapPointBuilderEx.ToGeometry();
                        mapPoints.Add(mapPoint);
                    }

                    // 创建结果点要素
                    GisTool.CreatePointFromMapPoint(mapPoints, sr, gdbPath, outName);
                    // 加载结果图层
                    MapCtlTool.AddLayerToMap(outPath);

                });

                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private void btn_help_Click(object sender, RoutedEventArgs e)
        {
            string url = "https://blog.csdn.net/xcc34452366/article/details/152044876";
            UITool.Link2Web(url);
        }

        private void combox_fc_DropDown(object sender, EventArgs e)
        {
            UITool.AddFeatureLayersToComboxPlus(combox_fc);
        }
    }
}
